package com.pig4cloud.pig.model.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.model.api.dto.ManagementDto;
import com.pig4cloud.pig.model.api.entity.ManagementEntity;
import com.pig4cloud.pig.model.api.entity.ModelServiceEntity;
import com.pig4cloud.pig.model.service.ManagementService;
import com.pig4cloud.pig.model.service.ModelServiceService;
import com.pig4cloud.pig.model.service.ProxyService;
import lombok.AllArgsConstructor;
import okhttp3.*;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 模型库管理表
 *
 * @author pig
 * @date 2024-06-06 14:42:19
 */
@Service
@AllArgsConstructor
public class ProxyServiceImpl  implements ProxyService {
	private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(5, TimeUnit.SECONDS).readTimeout(2, TimeUnit.MINUTES).connectionPool(new ConnectionPool(5,4,TimeUnit.SECONDS)).build();
	private final ManagementService managementService;
	private final ModelServiceService modelServiceService;

	/***
	* @Description: 测试模型
	* @Param: [management]
	* @return: com.pig4cloud.pig.common.core.util.R
	* @Author: marco
	* @Date: 2024/6/13
	*/
	@Override
	public String test(ManagementDto managementDto){
		String method = managementDto.getMethod();
		Request.Builder builder=getHeaders(managementDto.getHeader());
		String result = null;
        switch(method){
			case "GET":
				result=HttpGet(managementDto);
				break;
			case "POST":
				result=HttpPost(managementDto);
				break;
			default:
				break;
		}
		return result;
	}
	/***
	* @Description: 获取请求头信息
	* @Param: [header]
	* @return: okhttp3.Request.Builder
	* @Author: marco
	* @Date: 2024/6/17
	*/
	public Request.Builder getHeaders(String header){
		Request.Builder builder = new Request.Builder();
		JSONArray jsonArray = JSONArray.parseArray(header);
		jsonArray.forEach(o -> {
			JSONObject object = JSONObject.parseObject(o.toString());
			String name = object.getString("name");
			String defaultValue = object.getString("defaultValue");
			builder.addHeader(name, defaultValue);
		});
		return builder;
	}
	/***
	* @Description: Get 请求
	* @Param: [managementDto, httpClient]
	* @return: java.lang.String
	* @Author: marco
	* @Date: 2024/6/17
	*/
	public String HttpGet(ManagementDto managementDto){
		String parameterType = managementDto.getParameterType();
		String query=managementDto.getParameter();
		String target =managementDto.getUrl().split("/model")[1].toString();
		ManagementEntity managementEntity=managementService.getOne(Wrappers.<ManagementEntity>query()
				.lambda().eq(Boolean.TRUE,ManagementEntity::getUrl,target));
		ModelServiceEntity modelServiceEntity = modelServiceService.getById(managementEntity.getServiceId());
		target=modelServiceEntity.getProtocol()+"://"+modelServiceEntity.getHost() +":"+modelServiceEntity.getPort()+modelServiceEntity.getPath()+target;
		//from
		StringBuilder sb=new StringBuilder("?");
		if(parameterType.equals("0")){
			JSONArray objects = JSONArray.parseArray(query);
			objects.forEach(o -> {
				JSONObject object = JSONObject.parseObject(o.toString());
				String name = object.getString("name");
				String defaultValue = object.getString("defaultValue");
				sb.append(name).append("=").append(defaultValue).append("&");
			});
		}
		Request request = new Request.Builder()
				.url(target+sb)
				.get()
				.build();
		String data="";
		try {
			Response response =execute(request);;
			data=response.body().string();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return data;
	}
	public String HttpPost(ManagementDto managementDto){
		String target =managementDto.getUrl().split("/model")[1].toString();
		ManagementEntity managementEntity=managementService.getOne(Wrappers.<ManagementEntity>query()
				.lambda().eq(Boolean.TRUE,ManagementEntity::getUrl,target));
		ModelServiceEntity modelServiceEntity = modelServiceService.getById(managementEntity.getServiceId());
		target=modelServiceEntity.getProtocol()+"://"+modelServiceEntity.getHost() +":"+modelServiceEntity.getPort()+modelServiceEntity.getPath()+target;
		String query=managementDto.getParameter();
		System.out.println("输入参数："+JSONObject.parseObject(query));
		MediaType mediaType = MediaType.parse("application/json");
		RequestBody body = RequestBody.create(mediaType, JSONObject.parseObject(query).toString());
		Request request = new Request.Builder()
				.url(target.replace("/model",""))
				.method("POST", body)
				.addHeader("Content-Type", "application/json")
				.build();
		String result=null;
		try {
			Response response =execute(request);
			result=response.body().string();
			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	public static Response execute(Request request) throws IOException {
		return HTTP_CLIENT.newCall(request).execute();
	}
}
